package com.ruoyi.common.utils;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {

    /**
     * 添加src前缀路径
     * subPara 要替换的参数
     * oldStrObj 旧数据
     * prefixPath 新链接
     * */
    public static String addPrefixPath(String subPara,Object oldStrObj,String prefixPath){
        String path="";
        if(oldStrObj!="" && oldStrObj!=null){
            path=oldStrObj.toString();
            String regex =subPara+"=['|\"](.*?)['|\"]";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(path);
            // 字符串是否与正则表达式相匹配
            boolean rs = m.matches();
            if(!rs){
                Set<String> set=new HashSet<String>();
                while(m.find())
                {
                    set.add(m.group(0));
                }
                for(String str :set){
                    if(str.indexOf("http")<0){
                        String oldPath=str.substring(subPara.length()+2, str.length()-1);
                        if(oldPath!=null && oldPath.substring(0,1).contains("/")){
                            String aPrefixPath=prefixPath.substring(0,prefixPath.length()-1);
                            path= path.replace(str,subPara+"=\""+aPrefixPath+oldPath+"\"");
                        }else{
                            path=path.replace(str,subPara+"=\""+prefixPath+oldPath+"\"");
                        }
                    }
                }
            }
        }
        return path;
    }

    //Object转Map
    public static Map<String, Object> getObjectToMap(Object obj) {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        try{
            Class<?> clazz = obj.getClass();
            System.out.println(clazz);
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(obj);
                if (value == null){
                    value = "";
                }
                map.put(fieldName, value);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
}
